<template>
    <div class="msg_container">
      <el-form 
        class="el_form" 
        label-width="120px"
        :model="userData" 
        :rules="userRules" 
        ref="userFormRef"
        >
        <el-form-item label="" prop="avatar">
          <el-col :span="12" class="flex_row">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-change="handleAvatarChange"
              :on-success="handleAvatarSuccess"
              :auto-upload="false"
            >
              <!-- 只有在 userData.avatar 不为 null 时显示图片 -->
              <img v-if="userData.avatar" :src="userData.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <p class="tips">点击上传头像</p>
          </el-col>
        </el-form-item>
  
        <el-form-item label="昵称 :" prop="nickname">
          <el-col :span="10">
            <el-input type="text" v-model="userData.nickname" placeholder="请输入昵称"></el-input>
          </el-col>
          <p class="tips tipsColor">每个月只能修改一次昵称</p>
        </el-form-item>
  
        <el-form-item label="&nbsp;&nbsp;简介 :" prop="intor">
          <el-col :span="10">
            <textarea class="textarea" type="text" v-model="userData.introduction" placeholder="请输入简介"></textarea>
          </el-col>
        </el-form-item>
  
        <el-form-item>
          <button type="button" class="submit_btn" @click="submitFn">保存</button>
        </el-form-item>
        
      </el-form>
    </div>
  </template>
  
  <script setup>
  import { reactive, ref } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import { editInfo, getUserInfo } from '../../../api/user'
  import { upload } from '../../../api/upload'
  import config from '../../../utils/config'

  import { useUserStore } from '../../../store/user';
  const { setUsername, setToken, userState } = useUserStore()
  
//   const userData.avatar = ref(null) // 初始图片为空（不删除之前的图片）
  let isShowPic = ref(true)
  const userFormRef = ref(null)
  let count = 0
  
  let userData = reactive({
    avatar: '',
    nickname: '',
    introduction: ''
  })

  function resetUserData() {
    userData.avatar = ''
    userData.nickname = ''
    userData.introduction = ''
  }

  const fileMustUpload = (rule, value, callback) => {
    // if( !userData.avatar ) {
    //     callback('请上传图片')
    // }
    callback()
  }

  function getUserInfoFn() {
    getUserInfo().then(res => {
      console.log(res)
      const data = res.data.data
      if (res.status === 200) {
        userState.nickname = data.nickname
        userState.introduction = data.introduction
        userState.avatar = data.avatar
        ElMessage({
            message: '保存成功',
            type: 'success',
            icon: 'none',
            duration: 2 * 1000
        })
        resetUserData()
      }
    })
  }
  
  function submitFn() {
    userFormRef.value.validate((valid) => {
      if(valid) {
        editInfo(userData).then(res => {
          if(res.status === 200) {
            getUserInfoFn()
          } else {
            ElMessage({
              message: '获取用户信息失败',
              type: 'error',
              icon: 'none',
              duration: 2 * 1000
            })
          }
        })
      }
    })
  }
  
  const handleAvatarSuccess = () => {
    // 上传成功后的处理逻辑
  }
  
  const userRules = {
    avatar: [
      { required: false, validator: fileMustUpload, trigger: 'blur' }
    ],
    nickname: [
      { required: true, message: '请输入昵称', trigger: 'blur' }
    ]
  }
  
  // 处理文件选择变化
  // const handleAvatarChange = (file) => {
  //   console.log('file:', file)
  //   if (file && file.raw) {
  //     // 使用 URL.createObjectURL 来生成文件的临时 URL 并显示图片
  //     // if (isShowPic.value) {
  //     //   // userData.avatar = URL.createObjectURL(file.raw)
  //     // }
  //     // const fileData = {
  //     //   file,
  //     //   type: 'avatar'
  //     // }

  //     const fileFormData = new FormData()
  //     fileFormData.append('file', file)
  //     fileFormData.append('type', 'avatar')

  //     upload(fileFormData).then(res => {
  //       console.log('upload response:', res)
  //     }).catch(err => {
  //       console.error('Upload failed:', err);
  //     })
  //   }
  //   userFormRef.value.clearValidate('img')
  // }

  // 处理头像文件选择变化
  const handleAvatarChange = (file) => {
    count++
    console.log('执行了n',count,'次')
    console.log('file:', file)
    if (file && file.raw) {
      const fileFormData = new FormData()
      fileFormData.append('file', file.raw)   // 使用 raw 文件进行上传
      fileFormData.append('type', 'avatar')   // 上传类型
      
      upload(fileFormData).then(res => {
        console.log('上传头像：',res)
        if (res.status === 200) {
          userData.avatar = config.BaseImgUrl + res.data.src  // 更新头像 URL
        } else {
          ElMessage.error('头像上传失败')
        }
      }).catch(err => {
        // console.error('Upload failed:', err)
        ElMessage.error(err.response.data.msg)
      })
    }
      userFormRef.value.clearValidate('img')
  }
  
  // 文件上传前的验证
  const beforeAvatarUpload = (rawFile) => {
    const isImageType = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'].includes(rawFile.type)
    
    if (!isImageType) {
      ElMessage.error('头像图片必须是 JPG、PNG、JPEG 或 GIF 格式！')
      isShowPic.value = false
      return false // 阻止文件上传，但不会清空 userData.avatar
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('头像图片大小不能超过 2MB！')
      isShowPic.value = false
      return false // 阻止文件上传，但不会清空 userData.avatar
    } else {
      isShowPic.value = true
    }
    return true
  }
  </script>


<style scoped>
.flex_row {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
}
  .el_form {
    font-size: 16px;
  }

  .el_form .tips{
    font-size: 16px;
    margin-left: 20px;
  }

  .tipsColor {
    color:rgba(255, 255, 255, 0.6)
  }

  .msg_container {
    padding: 30px;
    box-sizing: border-box;
  }

.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    display: block;
  }

  :deep(.el-upload){
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all .5s;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #FFF;
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    background: #d9d9d9;
  }

.vertical-center {
  display: flex;
  align-items: center;  /* 垂直居中 */
  justify-content: center;  /* 水平居中（如果需要） */
  height: 100%;  /* 高度撑满 */
}

.textarea {
    width: 100%;
    height: 300px;
    background-color: #59596f;
    border: none;
    padding: 10px;
    box-sizing: border-box;
    border-radius: 5px;
    font-size: 18px;
    color: #FFF;
}
.submit_btn {
    width: 200px;
    height: 40px;
    line-height: 42px;
    text-align: center;
    color: #FFF;
    background-color: #e13f79;
    font-size: 18px;
    border-radius: 5px;
  }
</style>
  